package com.cityos.android.mystudynestedscroll.ui.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cityos.android.mystudynestedscroll.R
import com.cityos.android.mystudynestedscroll.databinding.FragmentListBinding
import com.cityos.android.mystudynestedscroll.databinding.ItemStrBinding

class ListFragment : Fragment() {
    companion object {
        @JvmStatic
        fun newInstance() = ListFragment().apply {
            arguments = Bundle().apply {}
        }
    }

    private val itemList = ArrayList<String>()
    private lateinit var mBinding: FragmentListBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        for (i in 0 .. 100) {
            itemList.add("item is $i")
        }
    }

    override fun onCreateView(inflater: LayoutInflater , container: ViewGroup? , savedInstanceState: Bundle?): View? {
        mBinding = FragmentListBinding.inflate(layoutInflater , container , false)
        return mBinding.root
    }


    override fun onViewCreated(view: View , savedInstanceState: Bundle?) {
        super.onViewCreated(view , savedInstanceState)
        mBinding.rv.apply {
            layoutManager = LinearLayoutManager(view.context)
            adapter = ItemAdapter(itemList)

        }
    }
}

class ItemAdapter(private val itemList: ArrayList<String>) : RecyclerView.Adapter<ItemViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup , viewType: Int): ItemViewHolder {
        val binding = ItemStrBinding.inflate(LayoutInflater.from(parent.context) , parent , false)
        return ItemViewHolder(binding)
    }

    override fun getItemCount() = itemList.size

    override fun onBindViewHolder(holder: ItemViewHolder , position: Int) {
        holder.onBindView(itemList[position])
    }
}


class ItemViewHolder(private val itemBinding: ItemStrBinding) : RecyclerView.ViewHolder(itemBinding.root) {
    fun onBindView(itemStr: String) {
        itemBinding.tv.text = itemStr
    }
}
